/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wsapi.commons;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView; 

/**
 * EXTJS 请求如果发生异常，返回json
 *
 * @author yangyan <y.os@qq.com>
 */
public class ExtJSExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String header = request.getHeader("X-Requested-With");

        if ("XMLHttpRequest".equals(header)) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);

            if (ex != null && ex instanceof org.apache.shiro.authz.UnauthorizedException) {
                // 无权限
                result.put("msg", "对不起，您无此操作权限");
            }

            if (ex != null && ex instanceof KnownException) {
                result.put("msg", ex.getMessage());
            }

            response.setContentType(MappingJackson2JsonView.DEFAULT_CONTENT_TYPE);
            response.setCharacterEncoding(JsonEncoding.UTF8.getJavaName());
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
            response.addDateHeader("Expires", 1L);
            try {
                new ObjectMapper().writeValue(response.getWriter(), result);
                return null;
            } catch (IOException ex1) {
                Logger.getLogger(ExtJSExceptionResolver.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
        return new ModelAndView(new RedirectView("/", true));
    }
}
